<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
// to-do: sales -> juris -> distributor selection
function sales_log_add_page() {
    return drupal_get_form('sales_log_edit_form');
}

function sales_log_edit_page($id) {
    return drupal_get_form('sales_log_edit_form', $id);
}

function sales_log_edit_form($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('sales_log', 'sales_log_id', $id);
        if (empty($record)) {
            drupal_set_message(t('销售日志不存在！'), 'status', FALSE);
            return $form;
        }
    }

    // 判断用户角色
    if(!nonghua_user_access('sales_log', 'view', $id, !empty($record) ? $record->author_uid:0,!empty($record) ? $record->salesman_id:0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    $form['sales_log_date'] = array(
        '#title' => '日志日期',
        '#type' => 'metercomm_date',
        '#default_value' => _date_db_2_form(!empty($record) ? $record->sales_log_date : ''),
        '#required' => TRUE,
        '#disabled'=> true,
    );
    $form['employee_list']   =  _insert_loginuser_choose_salesman_selection($user,!empty($record)?$record->salesman_id:$user->uid,true,'add');

    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
    $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5,true,  !empty($record) ? $record->addr_id:'','省,市,县必填');

    $form['addr_details'] = array(
        '#type' => 'textfield',
        '#title' => '详细地址',
        '#size' => 32,
        '#maxlength' => 32,
        '#default_value' => !empty($record) ? $record->addr_details:'',
    );

    $form['client'] = array(
        '#type' => 'textfield',
        '#title' => '客户名称',
        '#size' => 32,
        '#maxlength' => 20,
        '#default_value' => !empty($record) ? $record->client:'',
    );

    $form['contact'] = array(
        '#type' => 'textfield',
        '#title' => '联系人',
        '#size' => 32,
        '#maxlength' => 20,
        '#default_value' => !empty($record) ? $record->contact:'',
    );

    $form['phone'] = array(
        '#type' => 'textfield',
        '#title' => '联系电话',
        '#size' => 32,
        '#maxlength' => 20,
        '#default_value' => !empty($record) ? $record->phone:'',
    );

    $form['work_title'] = array(
        '#type' => 'textfield',
        '#title' => '工作内容主题（20字内）',
        '#size' => 32,
        '#maxlength' => 20,
        '#required' => true,
        '#default_value' => !empty($record) ? $record->work_title:'',
    );

    $form['work_details'] = array(
        '#type' => 'textarea',
        '#title' => '详情或心得（200字内）',
        '#cols' => 32,
        '#rows' => 2,
        '#maxlength' => 200,
        '#default_value' => !empty($record) ? $record->work_details:'',
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($record) ? '修改' : '添加',
        '#access' => nonghua_user_access('sales_log', 'edit', $id, !empty($record) ? $record->author_uid:0,!empty($record) ? $record->salesman_id:0) ,
    );
    return $form;
}

function sales_log_edit_form_validate($form, &$form_state) {

    if(empty($form_state['values']['employee_list'])){
        form_set_error('employee_list','销售员不能为空');
    }
    _address_element_validate($form_state);

}

function sales_log_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address =  _get_address_id_from_autocomplete_select($form_state);
    $log_addr = getIPLoc_QQ($_SERVER["REMOTE_ADDR"]) ;

    if (empty($id)) { //add new sales_log
        $nid = db_insert('sales_log') // Table name no longer needs {}
        ->fields(array(
            'sales_log_date' => _date_form_2_db($form_state['values']['sales_log_date']),
            'salesman_id' => $form_state['values']['employee_list'],
            'addr_id' => $address,
            'addr_details' => $form_state['values']['addr_details'],
            'client' => $form_state['values']['client'],
            'contact' => $form_state['values']['contact'],
            'phone' => $form_state['values']['phone'],
            'work_title' => $form_state['values']['work_title'],
            'work_details' => $form_state['values']['work_details'],
            'log_ip' => $_SERVER["REMOTE_ADDR"],
            'log_addr' => $log_addr,
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
        }
//        drupal_goto('sales/sales_log/list');
    } else {
        $nid = db_update('sales_log') // edit exsting store. todo: update only modified fields
        ->fields(array(
            'sales_log_date' => _date_form_2_db($form_state['values']['sales_log_date']),
            'salesman_id' => $form_state['values']['employee_list'],
            'addr_id' => $address,
            'addr_details' => $form_state['values']['addr_details'],
            'client' => $form_state['values']['client'],
            'contact' => $form_state['values']['contact'],
            'phone' => $form_state['values']['phone'],
            'work_title' => $form_state['values']['work_title'],
            'work_details' => $form_state['values']['work_details'],
            'log_ip' => $_SERVER["REMOTE_ADDR"],
            'log_addr' => $log_addr,
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            -> condition('sales_log_id',$id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
//        drupal_goto('sales/sales_log/list');
    }
}
//新浪接口------通过ip获取地理位置
function getIPLoc_sina($queryIP){
    $url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$queryIP;
    $ch = curl_init($url);     //
    curl_setopt($ch,CURLOPT_ENCODING ,'utf8');
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
     // 获取数据返回
    $location = curl_exec($ch);
    $location = json_decode($location);
    curl_close($ch);
    $loc = "";
    if(empty($location) or $location === false )
        return "";
    print_r($location);
    if (empty($location->desc)) {
        $loc = $location->province.$location->city.$location->district.$location->isp;
    }else{
        $loc = $location->desc;
    }
    return $loc;
}

function getIPLoc_QQ($queryIP){
    $url = 'http://ip.qq.com/cgi-bin/searchip?searchip1='.$queryIP;
    $ch = curl_init($url);
    curl_setopt($ch,CURLOPT_ENCODING ,'gb2312');
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
    $result = curl_exec($ch);
    $result = mb_convert_encoding($result, "utf-8", "gb2312"); // 编码转换，否则乱码
    curl_close($ch);
    preg_match("@<span>(.*)</span></p>@iU",$result,$ipArray);
    $loc = $ipArray[1];
    return $loc;
}
